package com.jin10.controller;


import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.jin10.bean.BaseResponse;
import com.jin10.entity.ApiList;
import com.jin10.entity.Tag;
import com.jin10.service.IApiListService;
import com.jin10.service.ITagService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Objects;

/**
 * <p>
 * 标签表 前端控制器
 * </p>
 *
 * @author raofy
 * @since 2022-01-21
 */
@RestController
@RequestMapping("/tag")
public class TagController {

    @Autowired
    ITagService iTagService;

    @Autowired
    IApiListService iApiListService;

    @GetMapping("getById")
    public BaseResponse getById(@RequestParam Integer id) {
        if (Objects.nonNull(id)) {
            Tag result = iTagService.getById(id);
            LambdaUpdateWrapper<ApiList> wrapper = new LambdaUpdateWrapper<>();
            wrapper.eq(ApiList::getTagId, id);
            List<ApiList> list = iApiListService.list(wrapper);
            if (!list.isEmpty()) {
                result.setApis(list);
            }
            if (Objects.nonNull(result)) {
                return BaseResponse.ok(result);
            } else {
                return BaseResponse.error("没有该记录！");
            }
        } else {
            return BaseResponse.error("查询id不能为空！");
        }
    }


    @PostMapping("update")
    public BaseResponse addOne(@RequestBody Tag dto) {
        try {
            boolean update = iTagService.saveOrUpdateElement(dto);
            return BaseResponse.ok(update);
        } catch (DuplicateKeyException e) {
            return BaseResponse.error("新建标签重复了！");
        }

    }

    /**
     * 递归删除
     *
     * @param id
     * @return
     */
    @GetMapping("delete")
    public BaseResponse deleteOne(@RequestParam Integer id) {
        return BaseResponse.ok(iTagService.recurrentDelete(id));
    }

    /**
     * 获取目录树
     *
     * @return
     */
    @GetMapping("list")
    public BaseResponse getList() {
        return BaseResponse.ok(iTagService.getList());
    }
}
